import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { logger } from './logger.js';
import { config } from '../config/env.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 配置文件路径
const CONFIG_PATH = path.resolve(__dirname, '../../config.json');

// 监听配置文件变化
export function watchConfig() {
  // 如果配置文件不存在，创建一个默认的
  if (!fs.existsSync(CONFIG_PATH)) {
    const defaultConfig = {
      auth: {
        whitelist: config.auth.whitelist,
      },
    };
    fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaultConfig, null, 2));
  } else {
    const newConfig = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));

    // 更新白名单配置
    if (newConfig.auth?.whitelist) {
      config.auth.whitelist = newConfig.auth.whitelist;
      logger.info('加载白名单信息', { whitelist: config.auth.whitelist });
    }
  }

  // 监听配置文件变化
  fs.watch(CONFIG_PATH, async eventType => {
    if (eventType === 'change') {
      try {
        const newConfig = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));

        // 更新白名单配置
        if (newConfig.auth?.whitelist) {
          config.auth.whitelist = newConfig.auth.whitelist;
          logger.info('白名单配置已更新', { whitelist: config.auth.whitelist });
        }
      } catch (error) {
        logger.error('配置文件更新失败', { error });
      }
    }
  });

  logger.info('配置文件监听已启动', { path: CONFIG_PATH });
}
